<?php

namespace App\Http\Middleware;

use App\Helper\Http\StatusCode;
use App\Helper\Token\Token;
use Closure;
use Illuminate\Http\Request;

class ApiToken
{
    #当前token
    protected $tokenString;

    public function __construct(Request $request)
    {
        #初始化赋值
        $this->tokenString = $request->header('token');

    }

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        #登录验证
        self::checkLogin();
        return $next($request);
    }

    #登录验证
    private function checkLogin()
    {
        $user_id = getUserId();
        $prefix = env('REDIS_HOME_PREFIX');
        # 获取服务端token

        $token = (new Token())->checkToken($prefix, $user_id);
        if ($token == null) {
            self::code('凭证失效,请重新登录');
        }
        # 判断客户端和服务端token是否相等
        if ($token != $this->tokenString) {
            self::code('凭证过期,请重新登录');
        }
        # 通过验证, token顺延3天
        (new Token())->increase($prefix, $user_id,$this->tokenString);
    }

    private function code($msg)
    {
        $json['code'] = StatusCode::LOGIN_ERROR;
        $json['msg'] = $msg;
        $json['data'] = "";
        echo json_encode($json);
        die;
    }
}
